import React, {useState, useRef} from "react";
import {Button, Card, Image, Modal, Space, Table, Input, Tag, Switch, TableColumnsType} from "antd";
import {OrderData} from "@/vite-env";
import useOrderData from "@/hooks/get_order_data.ts";
import {SearchOutlined} from '@ant-design/icons';
import type {InputRef, TableColumnType} from 'antd';
import type {FilterDropdownProps} from 'antd/es/table/interface';
import Highlighter from 'react-highlight-words';

type DataIndex = keyof OrderData;

const Order_Data: React.FC = () => {
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef<InputRef>(null);

    const handleSearch = (
        selectedKeys: string[],
        confirm: FilterDropdownProps['confirm'],
        dataIndex: DataIndex,
    ) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };

    const handleReset = (clearFilters: () => void) => {
        clearFilters();
        setSearchText('');
    };

    const getColumnSearchProps = (dataIndex: DataIndex): TableColumnType<OrderData> => ({
        filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
            <div style={{padding: 8}} onKeyDown={(e) => e.stopPropagation()}>
                <Input
                    ref={searchInput}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
                    style={{marginBottom: 8, display: 'block'}}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
                        icon={<SearchOutlined/>}
                        size="small"
                        style={{width: 90}}
                    >
                        查询
                    </Button>
                    <Button
                        onClick={() => clearFilters && handleReset(clearFilters)}
                        size="small"
                        style={{width: 90}}
                    >
                        重置
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: (filtered: boolean) => (
            <SearchOutlined style={{color: filtered ? '#1677ff' : undefined}}/>
        ),
        onFilter: (value, record) =>
            (record as { [key: string]: any })[dataIndex]
                .toString()
                .toLowerCase()
                .includes((value as string).toLowerCase()),
        onFilterDropdownOpenChange: (visible) => {
            if (visible) {
                setTimeout(() => searchInput.current?.select(), 100);
            }
        },
        render: (text) =>
            searchedColumn === dataIndex ? (
                <Highlighter
                    highlightStyle={{backgroundColor: '#ffc069', padding: 0}}
                    searchWords={[searchText]}
                    autoEscape
                    textToHighlight={text ? text.toString() : ''}
                />
            ) : (
                text
            ),
    });
    // 点击修改
    const handleOk = () => {
        setIsModalOpen(false)
    };

    // 打开对话框
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [order_detail, setOrder_detail] = useState<OrderData>({})
    const handleDetail = (record: OrderData) => {
        setOrder_detail(record)
        setIsModalOpen(true)

    };
    const columns: TableColumnsType<OrderData> = [
        {
            title: '订单编号',
            dataIndex: 'order_id',
            key: 'order_id',
            render: (text) => <b>{text}</b>,
            width: 150,
            align: 'center'
        },
        {
            title: '商品名称',
            dataIndex: 'product_name',
            key: 'product_name',
            render: (text) => <b>{text}</b>,
            align: 'center',
            ...getColumnSearchProps('product_name'),

        },
        {
            title: '商品类型',
            dataIndex: 'product_type',
            key: 'product_type',
            ellipsis: true,
            align: 'center',
            ...getColumnSearchProps('product_type'),

        },
        {
            title: '订单状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (text) => <Tag color={text === 1 ? "green" : "red"}>{text === 1 ? "已发货" : "未发货"}</Tag>,
            filters: [
                {text: '已发货', value: '1'},
                {text: '未发货', value: '0'},
            ],
            onFilter: (value, record) => String(record.status) === value,
        },
        {
            title: '订单库存',
            dataIndex: 'stock_quantity',
            key: 'stock_quantity',
            align: 'center',
            render: (text) => <Tag>{text + '件'}</Tag>
        },
        {
            title: '订单时间',
            dataIndex: 'time',
            key: 'time',
            align: 'center',
            render: (text) => <Tag color={"blue"}>{text}</Tag>
        },
        {
            title: '操作',
            width: 300,
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button type="primary" onClick={() => handleDetail(record)}>详情</Button>
                    <Button type="primary" danger>删除</Button>
                    {record.status === 0 && (
                        <Button>马上发货</Button>
                    )}
                </Space>
            ),
        },
    ];
    // 获取商品数据
    const [order_data] = useOrderData()
    // 修改状态
    const onChangeStatus = (checked: boolean) => {
        console.log(`switch to ${checked}`);
    };
    return (
        <Card
            style={{
                width: '100%',
            }}
        >
            <Table sticky={true} columns={columns} dataSource={order_data} scroll={{y: 530}}
                   onChange={() => {
                   }}
                   pagination={{
                       pageSize: 20,
                   }}/>
            <Modal title="下单人信息" open={isModalOpen} onOk={handleOk} onCancel={() => setIsModalOpen(false)}
                   width={600}
                   okText={"确定"} cancelText={"取消"}>
                <div style={{display: 'flex', width: '100%', alignItems: 'center'}}>
                    <div>
                        <Image width={100} src={order_detail.image}/>
                    </div>
                    <div style={{marginLeft: '20px'}}>
                        <p>商品名称 :{order_detail.product_name}</p>
                        <p>商品类型 :{order_detail.product_type}</p>
                        <p>商品价格 :{order_detail.price}</p>
                    </div>
                </div>
                <div style={{marginLeft: '20px'}}>
                    <p>订单编号：{order_detail.order_id}</p>
                    <p>用户名：{order_detail.username}</p>
                    <p>用户地址：{order_detail.address}</p>
                    <p>用户电话：{order_detail.phone_number}</p>
                    <p>订单库存：{order_detail.stock_quantity}</p>
                    <div> 是否发货： <Switch checkedChildren={'已发货'} unCheckedChildren={'未发货'}
                                            checked={order_detail.status === 1} onChange={onChangeStatus}/></div>

                </div>
            </Modal>
        </Card>
    )
}

export default Order_Data